package com.chengyu.core.service.impl;


import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.core.util.URLUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.chengyu.core.dao.FranchiseDao;
import com.chengyu.core.domain.CommonConstant;
import com.chengyu.core.entity.CommonPage;
import com.chengyu.core.exception.CommonException;
import com.chengyu.core.model.Franchise;
import com.chengyu.core.request.PageParamRequest;
import com.chengyu.core.service.FranchiseService;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 * 援助 服务实现类
 * </p>
 *
 * @author wenlj
 * @since 2023-10-29
 */
@Service
public class FranchiseServiceImpl extends ServiceImpl<FranchiseDao, Franchise> implements FranchiseService {

    @Autowired
    private FranchiseDao dao;


    /**
     * 获取列表
     *
     * @param request          请求参数
     * @param pageParamRequest 分页参数
     * @return PageInfo
     */
    @Override
    public PageInfo<Franchise> getList(Franchise request, PageParamRequest pageParamRequest) {
        Page<Franchise> FranchisePage = PageHelper.startPage(pageParamRequest.getPage(), pageParamRequest.getLimit());



        LambdaQueryWrapper<Franchise> lqw = Wrappers.lambdaQuery();



        if (ObjectUtil.isNotNull(request.getMemberId())) {
            lqw.eq(Franchise::getMemberId, request.getMemberId());
        }

//        if (ObjectUtil.isNotNull(request.getType())) {
//            lqw.eq(Franchise::getType, request.getType());
//        }
//        if (StrUtil.isNotBlank(request.getTitle())) {
//            String title = URLUtil.decode(request.getTitle());
//            lqw.like(Franchise::getTitle, title);
//        }
//        if (StrUtil.isNotBlank(request.getAuthor())) {
//            lqw.eq(Franchise::getAuthor, URLUtil.decode(request.getAuthor()));
//        }

        if (request.getStatus()!=null) {
            lqw.eq(Franchise::getStatus, request.getStatus());
        }



//        lqw.eq(Franchise::getIsDel, false);
        lqw.orderByDesc(Franchise::getId);
        List<Franchise> FranchiseList = dao.selectList(lqw);

        List<Franchise> responseList = new ArrayList<>();
        if (CollUtil.isEmpty(FranchiseList)) {
            return CommonPage.copyPageInfo(FranchisePage, responseList);
        }
        for (Franchise Franchise : FranchiseList) {
            Franchise response = new Franchise();
            BeanUtils.copyProperties(Franchise, response);
            responseList.add(response);
        }
        return CommonPage.copyPageInfo(FranchisePage, responseList);
    }

//
//    @Override
//    public PageInfo<Franchise> getList(String cid, PageParamRequest pageParamRequest) {
//        Page<Franchise> FranchisePage = PageHelper.startPage(pageParamRequest.getPage(), pageParamRequest.getLimit());
//
//        LambdaQueryWrapper<Franchise> lqw = Wrappers.lambdaQuery();
//
//
////        lqw.eq(Franchise::getCid, cid);
//        lqw.eq(Franchise::getStatus, true);
//        lqw.eq(Franchise::getIsDel, false);
//        lqw.orderByDesc(Franchise::getSort, Franchise::getId).orderByDesc(Franchise::getVisit).orderByDesc(Franchise::getCreateTime);
//        List<Franchise> FranchiseList = dao.selectList(lqw);
//        if (CollUtil.isEmpty(FranchiseList)) {
//            return CommonPage.copyPageInfo(FranchisePage, CollUtil.newArrayList());
//        }
//        List<Franchise> responseList = FranchiseList.stream().map(e -> {
//            Franchise FranchiseResponse = new Franchise();
//            BeanUtils.copyProperties(e, FranchiseResponse);
//            return FranchiseResponse;
//        }).collect(Collectors.toList());
//        return CommonPage.copyPageInfo(FranchisePage, responseList);
//    }


    /**
     * 查询详情
     *
     * @param id Integer
     * @return FranchiseVo
     */
    @Override
    public Franchise getVoByFront(Integer id)  {
        Franchise pmsFranchise = getById(id);
        if (ObjectUtil.isNull(pmsFranchise) || pmsFranchise.getIsDel()==1) {
            throw new CommonException("不存在");
        }
//        if (pmsFranchise.getStatus()==0) {
//            throw new CommonException("不存在");
//        }
        Franchise FranchiseResponse = new Franchise();
        BeanUtils.copyProperties(pmsFranchise, FranchiseResponse);
//        if (addFranchiseVisit(id)) {
//            logger.error("增加阅读次数失败，id = {}", id);
//        }
        return FranchiseResponse;
    }

    /**
     * 获取详情
     *
     * @param id id
     * @return Franchise
     */
    @Override
    public Franchise getDetail(Integer id) {
        Franchise Franchise = getByIdException(id);
        Franchise response = new Franchise();
        BeanUtils.copyProperties(Franchise, response);
        return response;
    }



    /**
     * 增加浏览次数
     *
     * @param id id
     */
    private Boolean addFranchiseVisit(Integer id) {
        UpdateWrapper<Franchise> wrapper = Wrappers.update();
        wrapper.setSql("visit = visit + 1");
        wrapper.eq("id", id);
        return update(wrapper);
    }

    /**
     * 获取移动端banner列表
     *
     * @return List<Franchise>
     */
    @Override
    public List<Franchise> getBannerList() {
        int FranchiseBannerLimit = 5;
        // 根据配置控制banner的数量
//        String FranchiseBannerLimitString = systemConfigService.getValueByKey(SysConfigConstants.Franchise_BANNER_LIMIT);
//        if (StrUtil.isNotBlank(FranchiseBannerLimitString)) {
//            FranchiseBannerLimit = Integer.parseInt(FranchiseBannerLimitString);
//        }
        LambdaQueryWrapper<Franchise> lqw = Wrappers.lambdaQuery();
//        lqw.select(Franchise::getId, Franchise::getCover, Franchise::getTitle);
//        lqw.eq(Franchise::getIsBanner, true);
        lqw.eq(Franchise::getStatus, true);
        lqw.eq(Franchise::getIsDel, false);
        lqw.orderByDesc(Franchise::getSort, Franchise::getId);
        lqw.last(" limit " + FranchiseBannerLimit);
        return dao.selectList(lqw);
    }

    /**
     * 获取移动端热门列表
     *
     * @return List<Franchise>
     */
    @Override
    public List<Franchise> getHotList() {
        LambdaQueryWrapper<Franchise> lqw = Wrappers.lambdaQuery();
//        lqw.select(Franchise::getId, Franchise::getCover, Franchise::getTitle, Franchise::getCreateTime);
//        lqw.eq(Franchise::getIsHot, true);
        lqw.eq(Franchise::getStatus, true);
        lqw.eq(Franchise::getIsDel, false);
        lqw.orderByDesc(Franchise::getSort, Franchise::getId);
        lqw.last(" limit 20");
        List<Franchise> FranchiseList = dao.selectList(lqw);
        if (CollUtil.isEmpty(FranchiseList)) {
            return CollUtil.newArrayList();
        }
        return FranchiseList.stream().map(e -> {
            Franchise FranchiseResponse = new Franchise();
            BeanUtils.copyProperties(e, FranchiseResponse);
            return FranchiseResponse;
        }).collect(Collectors.toList());
    }

    /**
     * 新增
     *
     * @param request 新增参数
     * @return Boolean
     */
    @Override
    public Boolean create(Franchise request) {
        Franchise Franchise = new Franchise();
        BeanUtils.copyProperties(request, Franchise);
        Franchise.setId(null);
//        String cdnUrl = systemAttachmentService.getCdnUrl();
//        Franchise.setCover(systemAttachmentService.clearPrefix(Franchise.getCover(), cdnUrl));
//        Franchise.setContent(systemAttachmentService.clearPrefix(Franchise.getContent(), cdnUrl));
//        Franchise.setVisit(0L);
        return save(Franchise);
    }


    /**
     * 修改
     *
     * @param request 修改参数
     */
    @Override
    public Boolean updateFranchise(Franchise request) {
        if (ObjectUtil.isNull(request.getId())) {
            throw new CommonException("ID不能为空");
        }
        Franchise  Franchise  =  getByIdException(request.getId());
        if(Franchise.getMemberId().equals(request.getMemberId())){

//        Franchise Franchise = new Franchise();
            BeanUtils.copyProperties(request, Franchise);
//        String cdnUrl = systemAttachmentService.getCdnUrl();
//        Franchise.setCover(systemAttachmentService.clearPrefix(Franchise.getCover(), cdnUrl));
//        Franchise.setContent(systemAttachmentService.clearPrefix(Franchise.getContent(), cdnUrl));
            return updateById(Franchise);
        }else{
            throw new CommonException("操作错误");
        }
    }




    /**
     * 修改
     *
     * @param request 修改参数
     */
    @Override
    public Boolean pushFranchise(Franchise request) {
//        if (ObjectUtil.isNull(request.getId())) {
//            throw new CommonException("ID不能为空");
//        }
//        getByIdException(request.getId());
//        Franchise Franchise = new Franchise();
//        BeanUtils.copyProperties(request, Franchise);


//        String[] imagesdList = request.getImages().split(CommonConstant.DH_REGEX);
//
//        if(imagesdList!=null) request.setCover(imagesdList[0]);

        if(request.getId() == null){
               return  create(request);
        }else{
            return updateFranchise(request);
        }


    }



    /**
     * 删除
     *
     * @param id id
     * @return Boolean
     */
    @Override
    public Boolean deleteById(Integer id) {
        Franchise Franchise = getByIdException(id);
        Franchise.setIsDel(1);
        return updateById(Franchise);
    }


    @Override
    public Boolean deleteByIdWithMemberId(Integer id,Integer memberId) {
        Franchise Franchise = getByIdMemberIdException(id,memberId);

        System.out.println(id);
        System.out.println(memberId);


        if (memberId.equals(0) ) {
            throw new CommonException("操作错误1！！！！！！");
        }

        if (!memberId.equals(Franchise.getMemberId())) {
            throw new CommonException("操作错误2！！！！！！");
        }



        Franchise.setIsDel(1);
        return updateById(Franchise);
    }

    private Franchise getByIdException(Integer id) {
        Franchise Franchise = getById(id);
        if (ObjectUtil.isNull(Franchise) || Franchise.getIsDel()==1) {
            throw new CommonException("不存在");
        }
        return Franchise;
    }

    private Franchise getByIdMemberIdException(Integer id,Integer memberId) {
        Franchise Franchise = getById(id);

        Map<String, Object> map = new HashMap<>();
        map.put("id", id);
        map.put("member_id", memberId);
        List<Franchise> list = dao.selectByMap(map);

        list.forEach(System.out::println);



        if (ObjectUtil.isNull(Franchise) || Franchise.getIsDel()==1) {
            throw new CommonException("不存在");
        }
        return Franchise;
    }



    /**
     * 是否使用分类
     *
     * @param categoryId 分类ID
     * @return Boolean
     */
    @Override
    public Boolean isUseCategory(Integer categoryId) {
        LambdaQueryWrapper<Franchise> lqw = Wrappers.lambdaQuery();
//        lqw.eq(Franchise::getType, categoryId);
        lqw.eq(Franchise::getIsDel, false);
        lqw.last(" limit 1");
        Franchise Franchise = dao.selectOne(lqw);
        return ObjectUtil.isNotNull(Franchise);
    }

    /**
     * 获取首页新闻头条
     */
    @Override
    public List<Franchise> getIndexHeadline() {
        LambdaQueryWrapper<Franchise> lqw = Wrappers.lambdaQuery();
//        lqw.select(Franchise::getId, Franchise::getTitle);
//        lqw.eq(Franchise::getIsHot, true);
        lqw.eq(Franchise::getStatus, true);
        lqw.eq(Franchise::getIsDel, false);
        lqw.orderByDesc(Franchise::getSort);
        lqw.last(" limit 10");
        return dao.selectList(lqw);
    }

    /**
     * 开关
     * @param id id
     * @return Boolean
     */
    @Override
    public Boolean FranchiseSwitch(Integer id) {
        Franchise Franchise = getByIdException(id);
        Franchise.setStatus(Franchise.getStatus()==1?0:1);
        return updateById(Franchise);
    }
}
